package com.chuangjiangx.member.coupon.ddd.domain.service;

import com.alibaba.fastjson.JSONObject;
import com.chuangjiangx.commons.DateUtils;
import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.commons.wx.upload.WxUploadUtils;
import com.chuangjiangx.member.coupon.ddd.domain.exception.MbrCouponNotExistException;
import com.chuangjiangx.member.coupon.ddd.domain.model.*;
import com.chuangjiangx.member.coupon.ddd.domain.repository.MbrCouponRepository;
import com.chuangjiangx.member.coupon.ddd.domain.repository.MbrHasCouponRepository;
import com.chuangjiangx.member.coupon.dao.model.InMbrHasCoupon;
import com.chuangjiangx.member.basic.ddd.domain.service.MemberRedisDomainService;
import com.chuangjiangx.member.stored.ddd.domain.model.MbrOrderRepository;
import com.chuangjiangx.member.basic.ddd.domain.model.MemberId;
import com.chuangjiangx.member.basic.ddd.domain.model.MerchantId;
import com.chuangjiangx.member.common.utils.MbrKeyManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import weixin.popular.api.CardAPI;
import weixin.popular.bean.BaseResult;
import weixin.popular.bean.card.*;
import weixin.popular.bean.card.code.consume.CodeConsume;
import weixin.popular.bean.card.code.consume.CodeConsumeResult;
import weixin.popular.bean.card.code.get.CodeGet;
import weixin.popular.bean.card.code.get.CodeGetResult;
import weixin.popular.bean.card.code.unavailable.CodeUnavailable;
import weixin.popular.bean.card.create.CreateResult;
import weixin.popular.bean.card.get.GetCashResult;
import weixin.popular.bean.card.update.UpdateCash;
import weixin.popular.bean.card.update.UpdateResult;
import weixin.popular.util.JsonUtil;

import java.math.BigDecimal;
import java.util.*;

import static com.chuangjiangx.commons.constant.CompensatorBusinessConstant.WX_VERIFY_ERROR;
import static com.chuangjiangx.commons.constant.CompensatorConstant.MEMBER_MANAGER_API_KEY;

/**
 * @author cj-ch
 * @date 2018/4/13 下午3:19
 */
@Slf4j
@Service
public class CouponDomainService {
    @Autowired
    protected MbrHasCouponRepository mbrHasCouponRepository;
    @Autowired
    private MbrCouponRepository mbrCouponRepository;
    @Autowired
    private MbrOrderRepository mbrOrderRepository;
    @Autowired
    private MemberRedisDomainService memberRedisDomainService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${member.h5.domain:''}")
    private String memberH5Domain;

    @Autowired
    private Environment env;


    /**
     * 会员领取卡券，校验领取上限
     * @param memberId 会员id
     * @param couponNumber 卡券编号
     */
    @Transactional(rollbackFor = Exception.class)
    public MbrHasCoupon memberClaimCoupon(MemberId memberId, String couponNumber) {
        Objects.requireNonNull(memberId);
        Objects.requireNonNull(couponNumber);
        MbrCoupon mbrCoupon = mbrCouponRepository.fromCouponNumber(couponNumber);
        mbrCoupon.claimCheck();
        List<InMbrHasCoupon> inMbrHasCoupons = mbrHasCouponRepository.fromMbrCouponId(memberId, mbrCoupon.getId());
        //校验当前会员是否到领取上限

        if(null != mbrCoupon.getClaimUpperLimit()){
            if(inMbrHasCoupons.size() >= mbrCoupon.getClaimUpperLimit()){
                throw new BaseException("800100","您领取已达上限，不能贪多哦");
            }
        }
        if (mbrCoupon.getAvailInventory() == 0) {
            throw new BaseException("800101","卡券已领完");
        }

        //减少库存
        mbrCouponRepository.inventoryUpdate(mbrCoupon,mbrCoupon.getTotalInventory(),mbrCoupon.getAvailInventory() - 1);
        //生成mbr_has_coupon
        MbrHasCoupon coupon = new MbrHasCoupon(memberId,mbrCoupon.getId());
        mbrHasCouponRepository.save(coupon);
        return coupon;
    }

    /**
     * 确认核销优惠券
     */
    public void confirmUseCoupon(MbrHasCouponId mbrHasCouponId){
        MbrHasCoupon mbrHasCoupon = mbrHasCouponRepository.fromId(mbrHasCouponId);
        if(mbrHasCoupon == null){
            log.warn("确认核销优惠券:优惠券不存在!?");
            return ;
        } else {
            mbrHasCoupon.use();
            mbrHasCouponRepository.update(mbrHasCoupon);
            // 删除redis 中的记录
            redisTemplate.delete(MbrKeyManager.MBR_COUPON_LOCK_KEY + mbrHasCoupon.getVerifyCode());
            MbrCoupon mbrCoupon = mbrCouponRepository.fromId(mbrHasCoupon.getMbrCouponId());
            if(mbrCoupon.isSyncedWx()&&mbrHasCoupon.getWxSyncStatus()==WxSyncStatus.SYNCED){
                //核销微信卡券
                verifyWxCode(mbrCoupon,mbrHasCoupon,1,null);
            }
//            //发送卡券核销redis订阅消息
//            redisTemplate.convertAndSend("coupon_use_success",mbrHasCoupon.getVerifyCode());
        }
    }

    /**
     * 确认核销优惠券
     */
    public void confirmUseCoupon(String couponCode){
        MbrHasCoupon mbrHasCoupon = mbrHasCouponRepository.fromVerifyCode(couponCode);
        if(mbrHasCoupon == null){
            log.warn("确认核销优惠券:优惠券不存在!?");
            return ;
        }
        mbrHasCoupon.use();
        mbrHasCouponRepository.update(mbrHasCoupon);
        MbrCoupon mbrCoupon = mbrCouponRepository.fromId(mbrHasCoupon.getMbrCouponId());
        if(mbrCoupon.isSyncedWx()&&mbrHasCoupon.getWxSyncStatus()==WxSyncStatus.SYNCED){
            //核销微信卡券
            verifyWxCode(mbrCoupon,mbrHasCoupon,1,null);
        }
    }

    /**
     * 二维码推广--会员领劵
     * @param couponNumber 卡券编号
     * @return
     */
    public String pushCoupon(String couponNumber,Long merchantId) {
        if(StringUtils.isBlank(this.memberH5Domain)) {
            log.warn("客户未配置H5域名,不能生成领劵推广二维码!");
            return null;
        } else {
            return this.memberH5Domain + "/app/index.html#/couponDetails?couponNumber=" + couponNumber+"&merchantId=" + merchantId;
        }
    }

    /**
     * 解锁卡券
     * @param verifyCode 核销码
     */
    @Transactional(rollbackFor = Exception.class)
    public void unlockCoupon(String verifyCode){
        Objects.requireNonNull(verifyCode,"会员领取卡券id不能为空");
        MbrHasCoupon mbrHasCoupon = mbrHasCouponRepository.fromVerifyCode(verifyCode);
        if (mbrHasCoupon == null) {
            throw new MbrCouponNotExistException();
        }
        boolean unlock = mbrHasCoupon.unlock();
        if(unlock){
            this.mbrHasCouponRepository.update(mbrHasCoupon);
        }
//        //修改订单状态
//        MbrOrder mbrOrder = mbrOrderRepository.fromMbrHasCouponId(mbrHasCoupon.getId().getId());
//        if (mbrOrder == null) {
//            throw new BaseException("-1","订单不存在");
//        }
//        mbrOrder.changeStatus(MbrOrderStatus.CANCELLED);
//        mbrOrderRepository.update(mbrOrder);
    }

    /**
     * 新增代金券至微信
     * @param mbrCouponId 卡券id
     */
    public void createWxCashCard(MbrCouponId mbrCouponId, String merchantName){
        MbrCoupon mbrCoupon = mbrCouponRepository.fromId(mbrCouponId);
        if(mbrCoupon == null){
            throw new BaseException("","卡券不存在");
        }
        if(env.getProperty("member.h5.domain")==null){
            throw new BaseException("","会员H5地址配置项有误");
        }
        String accessToken = memberRedisDomainService.getMerchantAccessToken(mbrCoupon.getMerchantId().getId());
        String logourl = WxUploadUtils.uploadWxLogo(accessToken,mbrCoupon.getLogo());

        CashCard wxCashCard = new CashCard();
        Cash wxCash = createWxCash(mbrCoupon,logourl,merchantName);
        wxCashCard.setCash(wxCash);

        CreateResult createResult = CardAPI.create(accessToken,wxCashCard);

        if(createResult==null){
            throw new BaseException("","同步至微信卡包失败");
        }
        if(createResult.isSuccess()){
            mbrCoupon.syncWx(createResult.getCardId());
            mbrCouponRepository.update(mbrCoupon);
        }else{
            throw new BaseException("",createResult.getErrmsg());
        }
    }

    /**
     * 修改代金券至微信
     * @param mbrCouponId 卡券id
     */
    public void updateWxCashCard(MbrCouponId mbrCouponId,String merchantName){
        MbrCoupon mbrCoupon = mbrCouponRepository.fromId(mbrCouponId);
        if(mbrCoupon == null){
            throw new BaseException("","卡券不存在");
        }
        if(env.getProperty("member.h5.domain")==null){
            throw new BaseException("","会员H5地址配置项有误");
        }
        String accessToken = memberRedisDomainService.getMerchantAccessToken(mbrCoupon.getMerchantId().getId());
        String logourl = WxUploadUtils.uploadWxLogo(accessToken,mbrCoupon.getLogo());
        UpdateCash wxUpdateCard = new UpdateCash();
        Cash wxCash = createUpdateWxCash(mbrCoupon,logourl,merchantName);
        wxUpdateCard.setCash(wxCash);
        wxUpdateCard.setCardId(mbrCoupon.getWxCardId());

        UpdateResult updateResult = CardAPI.update(accessToken,wxUpdateCard);

        if(updateResult==null){
            throw new BaseException("","同步至微信卡包失败");
        }
        if(updateResult.isSuccess()){
            if(updateResult.getSendCheck()){
                mbrCoupon.auditWx();
            }
            mbrCouponRepository.update(mbrCoupon);
        }else{
            throw new BaseException("",updateResult.getErrmsg());
        }
    }

    /**
     * 检查同步至微信的卡券的审核状态
     * @param mbrHasCouponId 领取的卡券id
     */
    public void checkAuditStatus(Long mbrHasCouponId){
        Assert.notNull(mbrHasCouponId,"卡券id不能为空");
        MbrHasCoupon mbrHasCoupon = mbrHasCouponRepository.fromId(new MbrHasCouponId(mbrHasCouponId));
        MbrCoupon mbrCoupon = mbrCouponRepository.fromId(mbrHasCoupon.getMbrCouponId());
        if(mbrCoupon == null){
            throw new BaseException("","卡券不存在");
        }
        //同步至微信并且未审核状态
        if(mbrCoupon.isSyncedWx()&& WxAuditStatus.NOT_AUDITED.equals(mbrCoupon.getWxAuditStatus())){
            GetCashResult getCashResult = getWxCash(mbrCoupon.getWxCardId(),mbrCoupon.getMerchantId());
            if(getCashResult==null){
                log.warn("微信卡券详情查询超时");
            }else if(!getCashResult.isSuccess()){
                log.warn("微信卡券详情查询失败：{}",getCashResult.getErrmsg());
            }else{
                Optional<GetCashResult> result = Optional.of(getCashResult);
                String wxStatus = result.map(GetCashResult::getCard).map(CashCard::getCash).map(Cash::getBaseInfo).map(BaseInfo::getStatus).orElse("");
                if(WxCardStatus.CARD_STATUS_VERIFY_OK.code.equals(wxStatus)){
                    mbrCoupon.wxAuditSuccess();
                    mbrCouponRepository.update(mbrCoupon);
                }
            }
        }
    }

    /**
     * 创建卡券信息
     */
    private Cash createWxCash(MbrCoupon mbrCoupon,String logourl,String merchantName){
        Cash wxCash = new Cash();
        wxCash.setLeastCost(mbrCoupon.getMiniExpendLimit().intValue()*100);
        wxCash.setReduceCost(mbrCoupon.getAmount().intValue()*100);

        BaseInfo wxBaseInfo = new BaseInfo();
        wxBaseInfo.setLogoUrl(logourl);
        wxBaseInfo.setBrandName(merchantName.length()>12?merchantName.substring(0,12):merchantName);
        wxBaseInfo.setCodeType("CODE_TYPE_QRCODE");
        if(Objects.equals(mbrCoupon.getMiniExpendLimit(),null)||mbrCoupon.getMiniExpendLimit().compareTo(new BigDecimal(0))==0){
            wxBaseInfo.setTitle(mbrCoupon.getAmount().setScale( 0, BigDecimal.ROUND_UP ).toString()+"元代金券");
        }else{
            wxBaseInfo.setTitle("满"+mbrCoupon.getMiniExpendLimit().setScale( 0, BigDecimal.ROUND_UP ).toString()+"元减"+mbrCoupon.getAmount().setScale( 0, BigDecimal.ROUND_UP ).toString()+"元代金券");
        }
        wxBaseInfo.setColor(mbrCoupon.getWxColor());
        wxBaseInfo.setNotice("请出示二维码");
        wxBaseInfo.setDescription(mbrCoupon.getRemark()==null?"":mbrCoupon.getRemark());
        wxBaseInfo.setGetLimit(mbrCoupon.getClaimUpperLimit());
        wxBaseInfo.setUseCustomCode(true);
        wxBaseInfo.setBindOpenid(false);
        wxBaseInfo.setCanGiveFriend(false);
        wxBaseInfo.setCanShare(false);
        wxBaseInfo.setCenterTitle("立即使用");
        wxBaseInfo.setCenterSubTitle(mbrCoupon.getWxCenterSubTitle());
        wxBaseInfo.setCenterUrl(env.getProperty("member.h5.domain")+"/h5/pay/redirect-wx-cash?merchant_id="+mbrCoupon.getMerchantId().getId());
        wxBaseInfo.setCustomUrl(env.getProperty("member.h5.domain")+"/app/index.html#/login/"+mbrCoupon.getMerchantId().getId());
        wxBaseInfo.setCustomUrlName("会员中心");
        //时间信息
        BaseInfoDateInfo wxBaseInfoDateInfo = new BaseInfoDateInfo();
        if(ValidType.EFFECT_DAYS.equals(mbrCoupon.getValidType())){
            wxBaseInfoDateInfo.setType("DATE_TYPE_FIX_TERM");
            wxBaseInfoDateInfo.setFixedBeginTerm(0);
            wxBaseInfoDateInfo.setFixedTerm(mbrCoupon.getClaimedTime());
        }else{
            wxBaseInfoDateInfo.setType("DATE_TYPE_FIX_TIME_RANGE");
            wxBaseInfoDateInfo.setBeginTimestamp((int)(mbrCoupon.getValidTimeStart().getTime()/1000));
            wxBaseInfoDateInfo.setEndTimestamp((int)(mbrCoupon.getValidTimeEnd().getTime()/1000));
        }
        wxBaseInfo.setDateInfo(wxBaseInfoDateInfo);
        //库存信息
        BaseInfoSku wxBaseInfoSku = new BaseInfoSku();
        wxBaseInfoSku.setQuantity(mbrCoupon.getTotalInventory().intValue());
        wxBaseInfo.setSku(wxBaseInfoSku);

        wxCash.setBaseInfo(wxBaseInfo);

        AdvancedInfo wxAdvancedInfo = new AdvancedInfo();
        AdvancedInfoUseCondition wxAdvancedInfoUseCondition = new AdvancedInfoUseCondition();
        wxAdvancedInfoUseCondition.setCanUseWithOtherDiscount(false);
        wxAdvancedInfo.setUseCondition(wxAdvancedInfoUseCondition);
        List<AdvancedInfoTimeLimit> wxTimeLimit = new ArrayList<>();
        for(String week:mbrCoupon.getUseTimeWeek().split(",")){
            AdvancedInfoTimeLimit wxAdvancedInfoTimeLimit = new AdvancedInfoTimeLimit();
            if(!Objects.equals(WxCouponWeekType.get(week),null)){
                wxAdvancedInfoTimeLimit.setType(WxCouponWeekType.get(week).name);
                String[] time = mbrCoupon.getUseTimeDay().split("-");
                wxAdvancedInfoTimeLimit.setBeginHour(Integer.valueOf(time[0].split(":")[0]));
                wxAdvancedInfoTimeLimit.setBeginMinute(Integer.valueOf(time[0].split(":")[1]));
                wxAdvancedInfoTimeLimit.setEndHour(Integer.valueOf(time[1].split(":")[0]));
                wxAdvancedInfoTimeLimit.setEndMinute(Integer.valueOf(time[1].split(":")[1]));
            }
            wxTimeLimit.add(wxAdvancedInfoTimeLimit);
        }
        wxAdvancedInfo.setTimeLimit(wxTimeLimit);

        wxCash.setAdvancedInfo(wxAdvancedInfo);

        return wxCash;
    }

    /**
     * 创建更新卡券信息
     */
    private Cash createUpdateWxCash(MbrCoupon mbrCoupon,String logourl,String merchantName){
        Cash wxCash = new Cash();
        BaseInfo wxBaseInfo = new BaseInfo();
        wxBaseInfo.setLogoUrl(logourl);
        wxBaseInfo.setNotice("请出示二维码");
        wxBaseInfo.setDescription(mbrCoupon.getRemark()==null?"":mbrCoupon.getRemark());
        wxBaseInfo.setColor(mbrCoupon.getWxColor());
        wxBaseInfo.setCenterTitle("立即使用");
        wxBaseInfo.setCenterSubTitle(mbrCoupon.getWxCenterSubTitle());
        wxBaseInfo.setCenterUrl(env.getProperty("member.h5.domain")+"/h5/pay/redirect-wx-cash?merchant_id="+mbrCoupon.getMerchantId().getId());
        wxBaseInfo.setCustomUrl(env.getProperty("member.h5.domain")+"/app/index.html#/login/"+mbrCoupon.getMerchantId().getId());
        wxBaseInfo.setCustomUrlName("会员中心");
        wxBaseInfo.setCodeType("CODE_TYPE_QRCODE");
        wxBaseInfo.setGetLimit(mbrCoupon.getClaimUpperLimit());
        wxBaseInfo.setCanShare(false);
        wxBaseInfo.setCanGiveFriend(false);
        //时间信息
        BaseInfoDateInfo wxBaseInfoDateInfo = new BaseInfoDateInfo();
        if(ValidType.EFFECT_DAYS.equals(mbrCoupon.getValidType())){
            wxBaseInfoDateInfo.setType("DATE_TYPE_FIX_TERM");
            wxBaseInfoDateInfo.setFixedBeginTerm(0);
            wxBaseInfoDateInfo.setFixedTerm(mbrCoupon.getClaimedTime());
        }else{
            wxBaseInfoDateInfo.setType("DATE_TYPE_FIX_TIME_RANGE");
            wxBaseInfoDateInfo.setBeginTimestamp((int)(mbrCoupon.getValidTimeStart().getTime()/1000));
            wxBaseInfoDateInfo.setEndTimestamp((int)(mbrCoupon.getValidTimeEnd().getTime()/1000));
        }
        return wxCash;
    }


    /**
     * 核销卡券
     */
    private void verifyWxCode(MbrCoupon mbrCoupon,MbrHasCoupon mbrHasCoupon,int tryTimes,String errorMsg){
        if(tryTimes>3){
            //重试3次以上 记录错误补偿
            recordVerifyWxCodeError(mbrCoupon,mbrHasCoupon,errorMsg);
        }
        CodeGetResult codeGetResult = getWxCode(mbrCoupon.getWxCardId(),mbrHasCoupon.getVerifyCode(),mbrCoupon.getMerchantId());
        if(codeGetResult==null||!codeGetResult.isSuccess()||!codeGetResult.getCanConsume()){
            //微信返回出错或者不可核销 开始错误处理
            if(codeGetResult!=null&&(codeGetResult.getUserCardStatus().equals(WxUserCardStatus.DELETE.code)
                    ||codeGetResult.getUserCardStatus().equals(WxUserCardStatus.EXPIRE.code)
                    ||codeGetResult.getUserCardStatus().equals(WxUserCardStatus.UNAVAILABLE.code))){
                //返回有结果 状态为 刪除 超时 失效 算已失效
                mbrHasCoupon.wxUnavaliable();
                mbrHasCouponRepository.update(mbrHasCoupon);
            }else if(codeGetResult!=null&&codeGetResult.getUserCardStatus().equals(WxUserCardStatus.CONSUMED.code)){
                //返回有结果 状态为 已核销
                mbrHasCoupon.wxVerified();
                mbrHasCouponRepository.update(mbrHasCoupon);
            }else{
                //剩下为返回没结果 或者既不可核销 又不能确定无法使用的 手动设置其失效
                BaseResult unavailableResult = unavailableWxCode(mbrCoupon.getWxCardId(),mbrHasCoupon.getVerifyCode(),mbrCoupon.getMerchantId());
                if(unavailableResult==null||!unavailableResult.isSuccess()){
                    //失效出错 不可预计错误
                    if(unavailableResult!=null){
                        //打印错误原因
                        errorMsg = unavailableResult.getErrcode()+"："+unavailableResult.getErrmsg();
                        log.warn(errorMsg);
                    }
                    //核销模块重试
                    verifyWxCode(mbrCoupon,mbrHasCoupon,++tryTimes,errorMsg);
                }else{
                    //失效成功
                    mbrHasCoupon.wxUnavaliable();
                    mbrHasCouponRepository.update(mbrHasCoupon);
                }
            }
        }else{
            //微信返回可以核销 走核销
            CodeConsumeResult codeConsumeResult = consumeWxCode(mbrCoupon.getWxCardId(),mbrHasCoupon.getVerifyCode(),mbrCoupon.getMerchantId());
            if(codeConsumeResult==null||!codeConsumeResult.isSuccess()){
                //核销出错 走失效
                BaseResult unavailableResult = unavailableWxCode(mbrCoupon.getWxCardId(),mbrHasCoupon.getVerifyCode(),mbrCoupon.getMerchantId());
                if(unavailableResult==null||!unavailableResult.isSuccess()){
                    //失效也错误 模块重试
                    if(unavailableResult!=null){
                        errorMsg = unavailableResult.getErrcode() + "：" + unavailableResult.getErrmsg();
                    }
                    verifyWxCode(mbrCoupon,mbrHasCoupon,++tryTimes,errorMsg);
                }else{
                    //失效成功
                    mbrHasCoupon.wxUnavaliable();
                    mbrHasCouponRepository.update(mbrHasCoupon);
                }
            }else{
                //核销成功
                mbrHasCoupon.wxVerified();
                mbrHasCouponRepository.update(mbrHasCoupon);
            }
        }
    }

    /**
     * 核销卡券
     */
    public void verifyWxCode(MbrCouponId mbrCouponId,MbrHasCouponId mbrHasCouponId){
        MbrCoupon mbrCoupon = mbrCouponRepository.fromId(mbrCouponId);
        MbrHasCoupon mbrHasCoupon = mbrHasCouponRepository.fromId(mbrHasCouponId);
        verifyWxCode(mbrCoupon,mbrHasCoupon,1,null);
    }

    /**
     * 查询微信卡券
     */
    private CodeGetResult getWxCode(String wxCardId,String code,MerchantId merchantId) {
        int codegetcount=1;
        CodeGetResult codeGetResult = null;
        do {
            CodeGet codeGet = new CodeGet();
            codeGet.setCardId(wxCardId);
            codeGet.setCode(code);
            codeGet.setCheckConsume(false);
            String accessToken = memberRedisDomainService.getMerchantAccessToken(merchantId.getId());
            codeGetResult = CardAPI.codeGet(accessToken,codeGet);
            if(codeGetResult==null||!codeGetResult.isSuccess()){
                codegetcount++;
            }else{
                return codeGetResult;
            }
        }while (codegetcount<3);
        log.info("微信code查询结果返回："+ JsonUtil.toJSONString(codeGetResult));
        return codeGetResult;
    }

    /**
     * 失效微信卡券
     */
    private BaseResult unavailableWxCode(String wxCardId, String code, MerchantId merchantId) {
        CodeUnavailable codeUnavailable = new CodeUnavailable();
        codeUnavailable.setCardId(wxCardId);
        codeUnavailable.setCode(code);
        String accessToken = memberRedisDomainService.getMerchantAccessToken(merchantId.getId());
        BaseResult baseResult =  CardAPI.codeUnavailable(accessToken, codeUnavailable);
        log.info("微信code失效结果返回："+ JsonUtil.toJSONString(baseResult));
        return baseResult;
    }

    /**
     * 核销微信卡券
     */
    private CodeConsumeResult consumeWxCode(String wxCardId, String code, MerchantId merchantId) {
        CodeConsume codeConsume = new CodeConsume();
        codeConsume.setCardId(wxCardId);
        codeConsume.setCode(code);
        String accessToken = memberRedisDomainService.getMerchantAccessToken(merchantId.getId());
        CodeConsumeResult codeConsumeResult =  CardAPI.codeConsume(accessToken, codeConsume);
        log.info("微信code黑侠结果返回："+ JsonUtil.toJSONString(codeConsumeResult));
        return codeConsumeResult;
    }

    /**
     * 查询微信卡券详情
     */
    private GetCashResult getWxCash(String wxCardId,MerchantId merchantId) {
        int codegetcount=1;
        GetCashResult getCashResult = null;
        do {
            String accessToken = memberRedisDomainService.getMerchantAccessToken(merchantId.getId());
            getCashResult = (GetCashResult)CardAPI.getByCardId(accessToken,wxCardId);
            if(getCashResult==null||!getCashResult.isSuccess()){
                codegetcount++;
            }else{
                return getCashResult;
            }
        }while (codegetcount<3);
        log.info("微信cardId查询Cash结果返回："+ JsonUtil.toJSONString(getCashResult));
        return getCashResult;
    }

    /**
     * 核销卡券错误补偿记录
     */
    private void recordVerifyWxCodeError(MbrCoupon mbrCoupon,MbrHasCoupon mbrHasCoupon,String errorMsg){
        VerifyWxCodeCompensator verifyWxCodeCompensator = new VerifyWxCodeCompensator();
        verifyWxCodeCompensator.setBusiness(WX_VERIFY_ERROR);
        verifyWxCodeCompensator.setErrClass(this.getClass().toString());
        verifyWxCodeCompensator.setErrMessage(errorMsg);
        verifyWxCodeCompensator.setErrTime(DateUtils.toLocalDateTime(new Date()));
        VerifyWxCodeCompensator.VerifyWxCodeCompensatorData data = verifyWxCodeCompensator.new VerifyWxCodeCompensatorData();
        data.setMbrCouponId(mbrCoupon.getId().getId());
        data.setMbrHasCouponId(mbrHasCoupon.getId().getId());
        verifyWxCodeCompensator.setData(data);
        redisTemplate.opsForList().leftPush(MEMBER_MANAGER_API_KEY, JSONObject.toJSONString(verifyWxCodeCompensator));
    }
}
